package com.iflytek.cosmo.ocr.support.license.client;

import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.iflytek.cosmo.ocr.support.license.LicenseVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/2/3
 */
@Component
public class LicenseVerifier {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private List<AbstractClientLicenseProcessor> processors;

    /**
     * 验证授权码是否有效
     *
     * @param license 授权码
     *
     * @return
     */
    public boolean isLicenseValid(String license) {
        if (StrUtil.isBlank(license)) {
            return false;
        }

        ClientLicense decodeLicense = AbstractClientLicenseProcessor.decodeBaseInfo(license);
        for (AbstractClientLicenseProcessor processor : processors) {
            if (processor.supportVersion().equals(LicenseVersion.parseFromCode(decodeLicense.getVersion()))) {
                try {
                    ClientLicense licenseDetail = processor.decode(license);
                    if (licenseDetail != null) {
                        logger.debug("授权码验证通过, 信息: " + license);
                        return true;
                    }
                }
                catch (Exception e) {
                    logger.warn("授权码验证异常");
                    return false;
                }
            }
        }

        return false;
    }

}
